/**
 *	\file AKTTTAIPlayer.m
 *  
 *  \section desc_sec Description
 *  Description
 *  
 *  \if copyright
 *  	Copyright 2008 Ben Chen. All rights reserved.
 *  \endif
 *  
 *  \section hist_sec Change History:
 *  	-	1/13/08		BC		Created this file
 *  
 *  <hr>
 *  \addtogroup AnimalKingdom
 *  @{
 */

#import "AKTTT.h"
#import "AKTTTAIPlayer.h"

@implementation AKTTTAIPlayer

@synthesize side;

- (void)initCells
{
	int i;
	for (i = 0; i < 9; ++i)
	{
		cells[i].cell	= i;
		cells[i].piece	= NSNotFound;
		cells[i].side	= NSNotFound;
	}
}

- (id)initWithSide:(AKSideIndex)sideIndex
{
	self = [super init];
	
	if (self != nil) 
	{
		side = (sideIndex == AKTTTBlack) ? AKTTTBlack : AKTTTWhite;
		
		[self initCells];
	}
	
	return self;
}

- (void)think:(id)something
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int i;
	for (i = 0; i < 9; ++i)
	{
		//[NSThread sleepForTimeInterval:0.5];
		
		if (cells[i].piece == NSNotFound)
		{
			bestMove.piece		= 0;
			bestMove.side		= side;
			bestMove.srcCell	= NSNotFound;	// Since the piece is newly created.
			bestMove.dstCell	= i;
			
			break;
		}
		
		if ([[NSThread currentThread] isCancelled])
			[NSThread exit];
	}
	
	isThinking = NO;
	
	// Notify the observer that the best move is changed when this thread exits.
	[self performSelectorOnMainThread:@selector(willChangeValueForKey:) withObject:@"bestMove" waitUntilDone:NO];
	[self performSelectorOnMainThread:@selector(didChangeValueForKey:)	withObject:@"bestMove" waitUntilDone:NO];
	
	[pool release];
}

- (void)stopThinking
{
	if ([thinkingThread isExecuting])
		[thinkingThread cancel];
}

- (void)backToInitialState
{
	[self initCells];
}

- (BOOL)thinkNextMove
{
	BOOL retVal;
	
	if ([thinkingThread isExecuting])
		retVal = NO;
	else
	{
		if (thinkingThread)
			[thinkingThread release];
		
		thinkingThread = [[NSThread alloc] initWithTarget:self selector:@selector(think:) object:nil];
		[thinkingThread start];
		
		retVal = YES;
	}
	
	return retVal;
}

- (BOOL)performMove:(AKMove)newMove
{
	BOOL retVal = NO;
	
	if (cells[newMove.dstCell].piece == NSNotFound)
	{
		cells[newMove.dstCell].piece = newMove.piece;
		cells[newMove.dstCell].side  = newMove.side;
		
		retVal = YES;
	}
	
	return retVal;
}

/*
- (BOOL)canUndoLastMove
{
	return NO;
}

- (BOOL)undoLastMove
{
	return NO;
}
 */

#pragma mark KVC methods

- (AKMove)bestMove
{
	return bestMove;
}

@end

/** @} */